package com.gitee.faster.webdav.kernel.event;

import cn.hutool.core.io.resource.ResourceUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import java.awt.*;

/**
 * @author hongda.li
 */
@Slf4j
public class SystemPreparedListener implements EventListener<PreparedHomeEvent> {
    /**
     * 托盘图标存储路径
     */
    private static final String ICON_PATH = "static/image/icon.png";

    @Getter
    private static TrayIcon trayIcon;

    @Override
    public void doListen(PreparedHomeEvent event) {
        // 确保系统托盘是支持的
        if (!SystemTray.isSupported()) {
            log.error("当前操作系统不支持系统托盘");
            return;
        }

        // 创建托盘图标
        trayIcon = new TrayIcon(new ImageIcon(ResourceUtil.getResource(ICON_PATH)).getImage(), "FasterWebDav");

        // 图像自适应
        trayIcon.setImageAutoSize(true);

        // 双击系统托盘打开浏览器
        trayIcon.addActionListener(e -> event.httpWebServer().openWithBrowser());

        // 将托盘图标添加到系统托盘
        try {
            SystemTray.getSystemTray().add(trayIcon);
        } catch (AWTException e) {
            log.error("创建系统托盘失败", e);
        }

        // 发送启动通知
        NotificationEvent notificationEvent = new NotificationEvent();
        notificationEvent.setMessage("WebDav服务启动成功");
        notificationEvent.setMessageType(TrayIcon.MessageType.INFO);
        EventPublisher.getInstance().publishEvent(notificationEvent);
    }
}
